package commands

import (
	"errors"
	"strconv"
	"strings"
	"time"

	"github.com/larspensjo/config"
	"github.com/urfave/cli"

	"../flags"
	"../utils"
)

// Publish - call publish
func Publish(config utils.Config) cli.Command {
	return cli.Command{
		Name:     "publish",
		Usage:    "call publish",
		Category: "DEVELOP COMMANDS",
		Flags: []cli.Flag{
			flags.Flags["path"],
			cli.StringFlag{
				Name:  "message, m",
				Value: "no message",
				Usage: "with `MESSAGE`",
			},
		},
		Action: makeAction(config, publishAction),
	}
}

/*
## manager
# 建立 release(from dev) 分支
sgbm-cli publish

## develop
# 完成开发任务（in hotfixes/release/feature）
sgbm-cli publish
*/
func publishAction(conf utils.Config, git utils.Git, context *cli.Context) error {
	configResult, err := utils.LoadConfig(conf, git, "config")
	if err != nil {
		return err
	}
	var ownName, ownRole string
	ownName, err = configResult.String("session", conf.PcCode)
	if err != nil {
		return errors.New("Please login")
	}
	ownRole, err = configResult.String("user", ownName)
	if err != nil {
		return errors.New("Session Info Error")
	}
	var ver string
	ver, err = configResult.String("global", "ver")
	if err != nil {
		return errors.New("Session Info Error")
	}

	var masterName, devName, head string
	masterName, err = configResult.String("global", "master")
	if err != nil {
		return err
	}
	devName, err = configResult.String("global", "dev")
	if err != nil {
		return err
	}
	head, err = git.ThisBranch()
	if err != nil {
		return err
	}

	if head == masterName {
		return errors.New("master branch can't publish")
	} else if head == devName {
		if ("master" != ownRole) && ("manager" != ownRole) {
			return errors.New("Please login with master/manager")
		}

		var logResult *config.Config
		logResult, err = utils.LoadConfig(conf, git, "log")
		if err != nil {
			return err
		}
		var num int
		num, err = logResult.Int("common", "num")
		if err != nil {
			return err
		}

		TYPE := "release"
		num++
		ID := strconv.Itoa(num)
		BRANCH := TYPE + "--" + ID

		_, err = git.Execute(
			[]string{"pull", "--all"},
			[]string{"branch", BRANCH},
			[]string{"push", "-u", "origin", BRANCH},
		)
		if err != nil {
			return err
		}

		time := time.Now().Unix()
		TIME := strconv.FormatInt(time, 10)
		MESSAGE := context.String("message")

		return utils.AddConfig(conf, git, "log", func(c *config.Config) *config.Config {
			c.AddOption("common", "num", strconv.Itoa(num))

			TASK := "task-" + ID
			c.AddSection(TASK)
			ver, _ = utils.UpdateVersionMiddle(ver)
			c.AddOption(TASK, "name", "publish v"+ver+"-RELEASE")
			c.AddOption(TASK, "message", MESSAGE)
			c.AddOption(TASK, "publisher", ownName)
			c.AddOption(TASK, "worker", "[no user]")
			c.AddOption(TASK, "type", TYPE)
			c.AddOption(TASK, "create_time", TIME)
			c.AddOption(TASK, "branch", BRANCH)

			c.AddOption(TASK, "active", "true")

			c.AddOption(TASK, "finish_time", TIME)
			c.RemoveOption(TASK, "finish_user")
			return c
		})
	} else {
		ID := strings.Split(head, "--")[1]
		TASK := "task-" + ID
		time := time.Now().Unix()
		TIME := strconv.FormatInt(time, 10)
		return utils.AddConfig(conf, git, "log", func(c *config.Config) *config.Config {
			c.AddOption(TASK, "finish_user", ownName)
			c.AddOption(TASK, "finish_time", TIME)
			return c
		})
	}

	// -----------

	return nil
}
